package com.heartskyhigh.order.controller;

import com.heartskyhigh.order.VO.ResultVO;
import com.heartskyhigh.order.converter.OrderForm2OrderDTOConverter;
import com.heartskyhigh.order.dto.OrderDTO;
import com.heartskyhigh.order.enums.ResultEnum;
import com.heartskyhigh.order.exception.OrderException;
import com.heartskyhigh.order.form.OrderForm;
import com.heartskyhigh.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @author Luo Zhen
 * @create 2019-11-19 14:14
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/create")
    public ResultVO create(@Valid OrderForm orderForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error("【创建订单】参数不正确,orderForm={}", orderForm);
            throw new OrderException(1,
                    bindingResult.getFieldError().getDefaultMessage());
        }
        // orderForm --> orderDTO
        OrderDTO orderDTO = OrderForm2OrderDTOConverter.convert(orderForm);
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            log.error("【创建订单】购物车信息为空");
            throw new OrderException(ResultEnum.CART_EMPTY);
        }
        OrderDTO result = orderService.create(orderDTO);
        return ResultVO.ok(result.getOrderId());
    }

}
